package com.project.dao.Impl;

import com.project.bean.ClassBean;
import com.project.dao.IClassDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ClassDaoImpl extends BaseDao implements IClassDao {
    @Override
    public void addClass(ClassBean classBean) {
        this.setConnection();
        try {
            ps= con.prepareStatement("insert into c_class(c_name,c_date,c_teacher)" +
                    "values(?,?,?)");
            ps.setObject(1,classBean.getNameClass());
            ps.setObject(2,classBean.getDate());
            ps.setObject(3,classBean.getTeacher());
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }

    }

    @Override
    public List<ClassBean> findAll() {
        List<ClassBean> list=new ArrayList<>();
        this.setConnection();
        try {
            ps=con.prepareStatement("SELECT * FROM c_class");
            rs=ps.executeQuery();
            while (rs.next()){
                list.add(this.getClassBean());
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
        return list;
    }

    private ClassBean getClassBean() {
        ClassBean classBean = new ClassBean();
        try {
            classBean.setId(rs.getInt("pk_cId"));
            classBean.setNameClass(rs.getString("c_name"));
            classBean.setDate(LocalDate.parse(rs.getString("c_date")));
            classBean.setTeacher(rs.getString("c_teacher"));
            return classBean;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void del(int id) {
        this.setConnection();
        try {
            ps=con.prepareStatement("DELETE FROM c_class WHERE pk_cId= ?");
            ps.setObject(1,id);
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
    }
}
